#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "md5.h"
#include <stdint.h>

#define DEFAULT_PORT 9001
#define CHUNK_SIZE 4096
#define WRITE_BUF_SIZE (256 * 1024) // 256KB写缓冲区

void flush_write_buffer(FILE *fp, unsigned char *write_buf, size_t *write_buf_used) {
    if (*write_buf_used > 0) {
        fwrite(write_buf, 1, *write_buf_used, fp);
        *write_buf_used = 0;
    }
}

void recv_udp(int listen_port, FILE *fp) {
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket error");
        exit(1);
    }
    // 调大UDP缓冲区
    int bufsize = 8 * 1024 * 1024;
    setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
    setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
    struct sockaddr_in local_addr, src_addr;
    socklen_t addrlen = sizeof(src_addr);
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(listen_port);
    if (bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind error");
        close(sock);
        exit(1);
    }
    unsigned int expected_seq = 0;
    size_t received_packets = 0;
    size_t lost_packets = 0;
    unsigned char *write_buf = (unsigned char*)malloc(WRITE_BUF_SIZE);
    size_t write_buf_used = 0;
    while (1) {
        unsigned char recvbuf[CHUNK_SIZE + 4];
        ssize_t recvd = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&src_addr, &addrlen);
        if (recvd < 4) continue;
        unsigned int seq;
        memcpy(&seq, recvbuf, 4);
        if (seq == 0xFFFFFFFF) break; // 结束包
        size_t data_len = recvd - 4;
        if (seq == expected_seq) {
            if (write_buf_used + data_len > WRITE_BUF_SIZE) {
                flush_write_buffer(fp, write_buf, &write_buf_used);
            }
            memcpy(write_buf + write_buf_used, recvbuf + 4, data_len);
            write_buf_used += data_len;
            expected_seq++;
            received_packets++;
        } else if (seq > expected_seq) {
            lost_packets += (seq - expected_seq);
            expected_seq = seq + 1;
            if (write_buf_used + data_len > WRITE_BUF_SIZE) {
                flush_write_buffer(fp, write_buf, &write_buf_used);
            }
            memcpy(write_buf + write_buf_used, recvbuf + 4, data_len);
            write_buf_used += data_len;
            received_packets++;
        }
    }
    flush_write_buffer(fp, write_buf, &write_buf_used); // 写入剩余数据
    free(write_buf);
    printf("Receive finished.\n");
    printf("Total packets received: %zu\n", received_packets);
    printf("Lost packets: %zu\n", lost_packets);
    if (received_packets + lost_packets > 0) {
        double loss_rate = 100.0 * lost_packets / (received_packets + lost_packets);
        printf("Packet loss rate: %.2f%%\n", loss_rate);
    }
    close(sock);
}

void recv_tcp(int listen_port, FILE *fp, const char *save_path) {
    int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_sock < 0) {
        perror("socket error");
        exit(1);
    }
    struct sockaddr_in local_addr, client_addr;
    socklen_t addrlen = sizeof(client_addr);
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(listen_port);
    if (bind(listen_sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind error");
        close(listen_sock);
        exit(1);
    }
    if (listen(listen_sock, 1) < 0) {
        perror("listen error");
        close(listen_sock);
        exit(1);
    }
    printf("Waiting for TCP connection on port %d...\n", listen_port);
    int conn_sock = accept(listen_sock, (struct sockaddr*)&client_addr, &addrlen);
    if (conn_sock < 0) {
        perror("accept error");
        close(listen_sock);
        exit(1);
    }
    // 先接收8字节文件大小
    uint64_t filesize = 0;
    ssize_t r = recv(conn_sock, &filesize, sizeof(filesize), MSG_WAITALL);
    if (r != sizeof(filesize)) {
        printf("Failed to receive file size!\n");
        close(conn_sock);
        close(listen_sock);
        fclose(fp);
        return;
    }
    size_t total_received = 0;
    unsigned char buf[CHUNK_SIZE];
    unsigned char *write_buf = (unsigned char*)malloc(WRITE_BUF_SIZE);
    size_t write_buf_used = 0;
    while (total_received < filesize) {
        size_t to_read = (filesize - total_received > CHUNK_SIZE) ? CHUNK_SIZE : (filesize - total_received);
        ssize_t recvd = recv(conn_sock, buf, to_read, MSG_WAITALL);
        if (recvd <= 0) break;
        if (write_buf_used + recvd > WRITE_BUF_SIZE) {
            flush_write_buffer(fp, write_buf, &write_buf_used);
        }
        memcpy(write_buf + write_buf_used, buf, recvd);
        write_buf_used += recvd;
        total_received += recvd;
    }
    flush_write_buffer(fp, write_buf, &write_buf_used); // 写入剩余数据
    free(write_buf);
    printf("TCP receive finished. Total bytes: %zu\n", total_received);
    // 接收MD5校验值
    unsigned char md5_recv[16];
    ssize_t md5len = recv(conn_sock, md5_recv, 16, MSG_WAITALL);
    if (md5len != 16) {
        printf("Failed to receive MD5 checksum!\n");
    } else {
        // 计算本地文件MD5
        fp = fopen(save_path, "rb");
        if (!fp) {
            printf("Failed to open received.bin for MD5 check!\n");
        } else {
            MD5_CTX ctx;
            MD5Init(&ctx);
            unsigned char filebuf[4096];
            size_t n;
            while ((n = fread(filebuf, 1, sizeof(filebuf), fp)) > 0) {
                MD5Update(&ctx, filebuf, n);
            }
            unsigned char md5_local[16];
            MD5Final(md5_local, &ctx);
            int match = memcmp(md5_local, md5_recv, 16) == 0;
            printf("MD5 check: %s\n", match ? "PASS" : "FAIL");
        }
    }
    close(conn_sock);
    close(listen_sock);
}

int main(int argc, char *argv[]) {
    const char *protocol = "udp";
    int listen_port = DEFAULT_PORT;
    const char *save_path = "./receiveddata/received.bin";
    if (argc > 1) protocol = argv[1];
    if (argc > 2) listen_port = atoi(argv[2]);
    if (argc > 3) save_path = argv[3];
    FILE *fp = fopen(save_path, "wb");
    if (!fp) {
        perror("Failed to open output file");
        return 1;
    }
    if (strcmp(protocol, "udp") == 0) {
        recv_udp(listen_port, fp);
    } else if (strcmp(protocol, "tcp") == 0) {
        recv_tcp(listen_port, fp, save_path);
    } else {
        fprintf(stderr, "Unknown protocol: %s\n", protocol);
        fclose(fp);
        return 1;
    }
    fclose(fp);
    return 0;
}
